package com.icloud.cer.rest.config;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.util.XMLUtils;
import com.icloud.cer.rest.web.bean.ServerConfig;


public class ServerConfigHolder {
	private final Logger log = LoggerFactory.getLogger(ServerConfigHolder.class);
	
	private static ServerConfigHolder instance;
	private Map<String, ServerConfig> serverMap = new HashMap<String, ServerConfig>();
	private List<String> blackIpList = new ArrayList<String>();
	
	public static synchronized ServerConfigHolder getInstance() {
		if (instance == null)
			instance = new ServerConfigHolder();
		return instance;
	}
	
	public void initServerConfig(String fileName) {
		InputStream in = ServerConfigHolder.class.getClassLoader().getResourceAsStream(fileName);
		ServerConfig config = XMLUtils.getServerConfig(in);
		if(config == null) {
			log.error("parse server config file:" + fileName + " error.");
			return;
		}
		serverMap.put(config.getId(), config);
	}
	
	public void initBlackIpList(String fileName) {
		refreshBlackIpList(fileName);
	}
	
	public void refreshBlackIpList(String fileName){
		InputStream in = ServerConfigHolder.class.getClassLoader().getResourceAsStream(fileName);
		blackIpList = XMLUtils.getBlackIpList(in);
		if(blackIpList == null || blackIpList.size() == 0) {
			log.error("parse black ip list config file:" + fileName + " error.");
			return;
		}
	}
	
	public Map<String, ServerConfig> getServerMap() {
		return serverMap;
	}
	
	public ServerConfig getServerConfig(String id) {
		return serverMap.get(id);
	}
	
	/**
	 * 目前只有一台server
	 * @return
	 */
	public ServerConfig getSingleServerConfig() {
		for(Entry<String, ServerConfig> entry : serverMap.entrySet()) {
			return entry.getValue();
		}
		return null;
	}
	
	public List<String> getBlackIpList() {
		return blackIpList;
	}
	
	public List<String> addBlackIp(String ip) {
		blackIpList.add(ip);
		return blackIpList;
	}
	
}
